package com.google.code.hibernate.rest.example;

import java.io.Serializable;
import java.util.Properties;

import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.IncrementGenerator;
import org.hibernate.type.Type;

/**
 * 
 * @author wangzijian
 * 
 */
public class SpecifiableIdentifierGenerator extends IncrementGenerator {

	public static final String NAME = "com.google.code.hibernate.rest.example.SpecifiableIdentifierGenerator";

	private String entityName;

	@Override
	public synchronized Serializable generate(SessionImplementor session, Object object) throws HibernateException {
		final Serializable id = session.getEntityPersister(entityName, object).getIdentifier(object, EntityMode.POJO);
		if (id == null) {
			return super.generate(session, object);
		}
		return id;
	}

	@Override
	public void configure(Type type, Properties params, Dialect dialect) throws MappingException {
		super.configure(type, params, dialect);
		entityName = params.getProperty(ENTITY_NAME);
		if (entityName == null) {
			throw new MappingException("no entity name");
		}
	}
}
